//菜单栏
const menu = {
    default_openeds: [],
    items: [
        {
            index: 'default',
            icon: 'fa fa-music',
            title: '默认页面',
        },
    ]
}

//参考资料
const tutorials = [
    {
        title: '【UTAU技术贴】用记事本打开ust，会是什么样子？Script方式打开UST如何看懂？',
        href: 'https://www.bilibili.com/read/cv10987379/',
        icon: 'el-icon-document',
    },
    {
        title: '汉语拼音音节_百度百科',
        href: 'https://baike.baidu.com/item/%E6%B1%89%E8%AF%AD%E6%8B%BC%E9%9F%B3%E9%9F%B3%E8%8A%82/9167981',
        icon: 'el-icon-document',
    },
]

//表单信息
var form = {
    tempo: 60.00,
    voice: 'uta',
    range: [45, 89],
    tool1: 'wavtool.exe',
    tool2: 'resampler.exe',
    number: 1000,
    oto_content: '',
}

//数据信息
var data = {
    version: '1.1.0',
    tutorial: false,
    loading: true,
    request: '',
    menu: menu,
    tutorials: tutorials,
    form: form,
    oto: false,
}

var app = new Vue({
    el: '#app',
    data: data,
    methods: {
        onSubmit: function () {
            //读取oto.ini内容获取音节表
            this.onSaveOto();
            if (form.oto_content.replace("\r", "").trim() == '') {
                alert('音节表不能为空');
                return;
            }
            if (form.voice.trim() == '') {
                alert('声库名称不能为空');
                return;
            }
            let lyrics = form.oto_content.replace("\r", "").trim().split("\n");
            lyrics = Array.from(new Set(lyrics));
            //生成ust内容
            let timestamp = new Date().getTime();
            let text = "[#SETTING]\n";
            text += "Tempo=" + form.tempo.toFixed(2) + "\n";
            text += "Tracks=1\n";
            text += "ProjectName=UTAU Random " + timestamp + "\n";
            text += "VoiceDir=%VOICE%" + form.voice + "\n";
            text += "OutFile=vocal_" + timestamp + ".wav\n";
            text += "CacheDir=vocal_" + timestamp + ".cache\n";
            text += "Tool1=" + form.tool1 + "\n";
            text += "Tool2=" + form.tool2 + "\n";
            let pa = [90, 80, 50, 10];
            //按数量生成音符
            for (let i = 0, lyric_index = 0; i < form.number; i++) {
                //生成音符编号
                text += "[#" + ('' + (i + 10000)).substring(1, 5) + "]\n";
                //随机生成音符长度
                var length = 1920;
                //第一个和最后一个是全音符，剩下的随机长度
                if (i > 0 && i < form.number - 1) {
                    length = randomRange(Math.floor(length * 0.75), Math.floor(length * 1.25));
                    var random = randomRange(0, 100);
                    //按概率生成二分、四分、八分、十六分音符
                    pa.forEach((item) => {
                        if (random < item)
                            length /= 2;
                    })
                }
                text += "Length=" + Math.floor(length) + "\n";
                var lyric = 'R';
                //第一个音符、每7个音符、最后一个音符为休止符，其他的逐个填充歌词
                if (i % 7 != 0 && i < form.number - 1) {
                    //每次扫描完一遍音节表，就乱序一次
                    if (lyric_index >= lyrics.length)
                        lyric_index = 0;
                    if (lyric_index == 0)
                        lyrics.sort(randomSort);
                    lyric = lyrics[lyric_index++];
                }
                text += "Lyric=" + lyric + "\n";
                //随机生成音高
                text += "NoteNum=" + randomRange(form.range[0], form.range[1] + 1) + "\n";
                text += "PreUtterance=\n";
                text += "Intensity=100\n";
                text += "Moduration=0\n";
            }
            text += "[#TRACKEND]\n";
            downloadText(text, form.voice + '_' + timestamp + ".ust");
        },
        onSaveOto: function () {
            let oto_content = form.oto_content.replace("\r", "").trim().split("\n");
            form.oto_content = '';
            for (let i = 0; i < oto_content.length; i++) {
                let lyric = oto_content[i];
                //先获取歌词名
                if (lyric.indexOf('=') > 0) {
                    lyric = lyric.substring(lyric.indexOf('=') + 1);
                    if (lyric.indexOf(',') >= 0)
                        lyric = lyric.substring(0, lyric.indexOf(','));
                    lyric = lyric.trim();
                    if (lyric == '')
                        lyric = oto_content[i];
                }
                //获取不到歌词名，以采样名为准
                if (lyric.indexOf('.wav') > 0)
                    lyric = lyric.substring(0, lyric.indexOf('.wav'));
                //没采样名，就直接原样作为歌词
                if (lyric != '')
                    form.oto_content += lyric + "\n";
            }
        },
        calc: function () {
            let items = [''];
            switch (this.request) {
                case 'form':
                    items = [];
                    break;
                default:
                    break;
            }
            return rnd(items);
        },
        formatRange: function (val) {
            let level = Math.floor(val / 12) - 1;
            let offset = val % 12;
            let array = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
            return array[offset] + level + ' (' + val + ')';
        }
    },

    computed: {
        collapse: function () {
            return document.body.clientWidth < 800;
        },
    },

    beforeCreate: function () {
        if (localStorage.tempo) {
            form.tempo = localStorage.tempo - 0;
        }
        if (localStorage.number) {
            form.number = localStorage.number - 0;
        }
        if (localStorage.voice) {
            form.voice = localStorage.voice;
        }
        if (localStorage.tool1) {
            form.tool1 = localStorage.tool1;
        }
        if (localStorage.tool2) {
            form.tool2 = localStorage.tool2;
        }
        if (localStorage.oto_content) {
            form.oto_content = localStorage.oto_content;
        }
        if (localStorage.range) {
            form.range = JSON.parse(localStorage.range);
        }
    },

    mounted: function () {
        this.loading = false;
        route();
    },

    watch: {
        'form.tempo'(newvalue) {
            localStorage.tempo = newvalue;
        },
        'form.number'(newvalue) {
            localStorage.number = newvalue;
        },
        'form.voice'(newvalue) {
            localStorage.voice = newvalue;
        },
        'form.tool1'(newvalue) {
            localStorage.tool1 = newvalue;
        },
        'form.tool2'(newvalue) {
            localStorage.tool2 = newvalue;
        },
        'form.oto_content'(newvalue) {
            localStorage.oto_content = newvalue;
        },
        'form.range'(newvalue) {
            localStorage.range = JSON.stringify(newvalue);
        },
    }
});

function route() {
    var str = location.href;
    var num = str.indexOf("#");
    if (num < 0)
        data.request = 'default';
    else
        data.request = str.substring(num + 1);
    if (typeof (app) != "undefined")
        app.$message({
            message: '切换模式',
            type: 'success'
        });
}

function rnd(items) {
    return items[Math.floor(Math.random() * items.length)];
}

function randomSort(a, b) {
    return Math.random() > 0.5 ? -1 : 1;
}

function randomRange(a, b) {
    return a + Math.floor(Math.random() * (b - a));
}

function downloadText(text, filename) {
    const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
    const objectURL = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = objectURL;
    link.download = filename;
    link.click();
    URL.revokeObjectURL(objectURL);
}